<template>
  <div class="live-box">
    <VTcPlayer
      v-if="options.m3u8 && showVideo"
      ref="vTcPlayer"
      :options="options"
      class="player-wrapper"
      @load="onPlayLoad"
      @play="onPlayStart"
      @pause="onPlayPause"
      @error="onPlayError"
      @ended="onPlayEnd"
    />
    <LiveDialog
      v-if="showDialog !== ''"
      :show-dialog="showDialog"
      :audition-time="liveInfo.AuditionTime"
      :live-status="liveInfo.LiveStatus"
      @reTry="tryAgain"
      @goEnroll="goEnroll"
    />
    <img
      id="play-round"
      src="~assets/class/play_round.png"
      class="play-round"
      style="display: none;"
      :class="{'displayNone': !showVideo}"
    >
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { mapState } from 'vuex'
import { VTcPlayer, TcPlayer, TcPlayerOptions } from 'v-tcplayer'
import { loadScript, browser as browserInfo, isiOS, rem2px } from '@/lib/utils'
import { UAParser } from 'ua-parser-js'
import order from '@/mixins/order'
import mixins from 'vue-typed-mixins'
const parser = new UAParser()
const parsedUA = parser.getResult()
const deviceInfo = `H5@|@|${parsedUA.browser.name}@|${parsedUA.browser.version}`
console.log('VTcPlayer', VTcPlayer)
export default mixins(order).extend({
  components: {
    VTcPlayer,
    LiveDialog: () => import('components/Live/LiveDialog.vue'),
  },
  // eslint-disable-next-line vue/require-default-prop
  // eslint-disable-next-line vue/require-prop-types
  props: ['liveInfo'],
  data () {
    const coverImg = this.liveInfo.CourseImg
    return {
      SectionId: this.$route.query.sectionId,
      CourseId: this.$route.query.courseId,
      ClassId: this.$route.query.classId,
      player: null as any as TcPlayer,
      showVideo: false,
      showDialogTemp: '',
      watchedTime: 0,
      keyId: 0,
      playErrorReason: '',
      timer: 0, // 计时
      fromLastSubmitTime: 0,
      checkStateTimer: 0,
      currentStatus: 0,
      options: {
        hlsUrl: 'https://lib.baomitu.com/hls.js/0.12.4/hls.min.js',
        width: Math.floor(rem2px(9.36)),
        height: Math.floor(rem2px(5.24)),
        m3u8: '',
        autoplay: false,
        live: true,
        poster: { 'style': 'cover', 'src': coverImg || require('assets/default.jpg') },
        // x5_fullscreen: true,
        // x5_player: true,
        // x5_type: 'h5',
      },
      // options: {
      //   hlsUrl: 'https://lib.baomitu.com/hls.js/0.12.4/hls.min.js',
      //   width: Math.floor(rem2px(9.36)),
      //   height: Math.floor(rem2px(5.24)),
      //   m3u8: this.$route.query.m3u8 || 'http://5170.liveplay.myqcloud.com/live/5170_885bf6c55e12c66db005d0362bfa91b1.m3u8',
      //   live: true,
      //   autoplay: false,
      // },
    }
  },
  computed: {
    ...mapState(['userInfo', 'instInfo']),

    // 是否试听
    isAudition (): boolean {
      let that = this as any
      return !that.liveInfo.IsBuy && that.liveInfo.IsAudition
    },
    // 是否试听结束
    isAuditionEnd (): boolean {
      let that = this as any
      return that.isAudition && that.liveInfo.AuditionTime > 0 &&
        that.liveInfo.AuditionTime * 60 - that.liveInfo.HasAuditionLong <= that.watchedTime
    },
    // 直播状态判断dialog
    showDialog (): string {
      if (!this.liveInfo.IsBuy && !this.liveInfo.IsAudition) {
        return 'showApplyTip'
      }
      // 已登录但试听结束
      if ((this as any).userInfo.UserId !== '-1' && this.isAuditionEnd) {
        return 'showEnroll'
      }
      // 试听结束
      if (this.isAuditionEnd) {
        return 'goRegister'
      }
      if (this.currentStatus === 1) {
        this.$set(this.$data, 'showVideo', true)
        this.$emit('hasLiving')
        return ''
      }
      if (this.currentStatus === 2) {
        return 'showWillStart'
      }
      if (this.currentStatus === 3) {
        this.destroyPlayer()
        return 'showEnded'
      }
      if (this.currentStatus === 4) {
        return 'showIsComming'
      }
      if (this.currentStatus === 5) {
        this.destroyPlayer()
        this.checkState()
        return 'showPause'
      }
      if (this.showDialogTemp !== '') {
        return this.showDialogTemp
      }
      return ''
    },
  },
  created () {
    this.currentStatus = this.liveInfo.LiveStatus
    this.createPlayer()

    // 直播已结束和直播中不开启计时器
    if (this.currentStatus !== 3 && this.currentStatus !== 1) {
      this.checkState()
    }
  },
  beforeDestroy () {
    this.destroyPlayer()
  },
  methods: {
    // 创建播放器
    createPlayer (liveUrl ?: string) {
      if (this.currentStatus !== 1 || this.isAuditionEnd) {
        return
      }
      let currentLiveUrl = liveUrl || this.liveInfo.LiveUrlM3u8
      this.showVideo = true
      if (this.player) {
        this.player.load(currentLiveUrl)
      } else {
        this.$set(this.$data.options, 'm3u8', currentLiveUrl)
      }
      console.log('createPlayer', currentLiveUrl)

      // 在播放器中设置封面与暂停按钮
      setTimeout(() => {
        const cloneRound = document.getElementById('cloneRound') as HTMLDivElement
        if (cloneRound) {
          return
        }
        let vcpPoster = document.getElementsByClassName('vcp-poster')[0]
        let playRound = document.getElementById('play-round') as HTMLDivElement
        const playRoundClone = playRound.cloneNode(true) as HTMLDivElement
        playRoundClone.id = 'cloneRound'
        playRoundClone.style.display = 'block'
        if (vcpPoster && this.showVideo) {
          console.log('333333')
          vcpPoster.appendChild(playRoundClone)
        }
      }, 100)
    },

    // 销毁播放器
    destroyPlayer () {
      if (this.player) {
        this.stopTimer(true)
        this.player.fullscreen(false)
        this.player.destroy()
        this.player = null as any
        this.showVideo = false
      }
    },

    // 播放器加载中
    onPlayLoad () {
      console.log('onPlayLoad');
      (document.getElementsByClassName('vcp-loading')[0] as HTMLElement)
        .style.opacity = '1'
      this.player = (this.$refs.vTcPlayer as any).vTcPlayer
    },
    onResize () {
      console.log('======================')
    },
    // 开始播放
    onPlayStart () {
      console.log('onPlayStart')
      if (this.isAuditionEnd) {
        setTimeout(() => {
          this.player.pause()
        }, 10)
        return
      }
      (document.getElementsByClassName('vcp-loading')[0] as HTMLElement)
        .style.opacity = '0'
      this.startTimer()
      this.recordStartWatchTime()
    },
    // 暂停播放
    onPlayPause () {
      console.log('onPause')
      this.stopTimer(true)
    },
    // 播放失败
    onPlayError (err: any) {
      console.log('playError', err)
      this.stopTimer(true)
      this.showDialogTemp = 'showTryAgain'
      this.destroyPlayer()
      if (this.liveInfo.LiveStatus === 1) {
        this.playErrorReason = err.reason
      }
    },
    // 播放结束
    onPlayEnd () {
      this.player && this.player.fullscreen(false)
    },

    // 开始观看
    recordStartWatchTime () {
      // 已登录但试听结束
      if ((this as any).userInfo.UserId !== '-1' && this.isAuditionEnd) {
        this.showDialogTemp = 'showEnroll'
        return
      }
      // 试听结束
      if (this.isAuditionEnd) {
        this.showDialogTemp = 'goRegister'
        return
      }
      let url = 'Live/EnterVideoLive'
      let data: any = {
        VideoId: this.SectionId,
        Type: 3, // 3: M站
        ClassId: this.ClassId,
        DeviceInfo: deviceInfo,
      }
      if (!this.liveInfo.IsBuy) {
        url = 'Live/SubmitAuditionTime'
        data = {
          LiveId: this.SectionId,
          ViewType: 2, // 2:M站
          ClassId: this.ClassId,
        }
      }
      this.$axios({ url, data }, 2).then(res => {
        if (!this.liveInfo.IsBuy) {
          this.keyId = res
        }
      }, err => {
        if (err.ResultCode === 20007) {
          this.showDialogTemp = 'showLogin'
        }
      })
    },

    // 提交观看进度
    submitWatchTime (endWatch: boolean) {
      console.log('提交观看进度1', new Date())
      let url = 'Live/ExitVideoLive'
      let data: any = {
        VideoId: this.SectionId,
        Type: 3, // 3: M站
        CourseId: this.CourseId,
        ExitType: endWatch ? 2 : 1,
        ClassId: this.ClassId,
      }
      if (!this.liveInfo.IsBuy) {
        console.log('keykeyId', this.keyId)
        if (!this.keyId) {
          return Promise.resolve()
        }
        url = 'Live/ExitAuditionTime'
        data = {
          KeyId: this.keyId,
          ExitType: endWatch ? 2 : 1,
          ClassId: this.ClassId,
        }
      }
      this.keyId = 0
      return this.$axios({ url, data }, 1)
    },

    // 检查状态timer
    checkState () {
      // this.checkStateTimer = window.setInterval(this.checkLiveStateApi, 60 * 1000)
    },
    // 检查直播状态的接口
    checkLiveStateApi () {
      const checkLiveId = this.SectionId
      this.$axios({
        url: 'Live/CheckVideoState',
        data: {
          sectionId: checkLiveId,
          ClassId: this.ClassId,
        },
      }, 2).then(res => {
        if (res.LiveStatus === 1 && this.playErrorReason) {
          this.playErrorReason = ''
        }
        if (res.LiveStatus !== this.currentStatus ||
            res.LiveUrlM3u8 !== this.options.m3u8) {
          this.$set(this.$data, 'currentStatus', res.LiveStatus)
          this.$emit('curLiveStatus', this.currentStatus)
          // this.getLiveStatus(res.LiveStatus)
          this.createPlayer(res.LiveUrlM3u8)
          this.player && this.player.fullscreen(false)
        }
      }, err => {
        if (err.ResultCode === 20007) {
          this.showDialogTemp = 'showLogin'
        }
      })
    },

    // 停止检查计时器
    stopCheckStateTime () {
      if (this.checkStateTimer && this.liveInfo.LiveStatus !== 5) {
        console.log('stop checkStateTimer', this.currentStatus)
        window.clearInterval(this.checkStateTimer)
        this.checkStateTimer = 0
      }
    },

    // 开启计时器，每5分钟提交一次观看进度
    startTimer () {
      this.stopTimer(false)
      this.timer = window.setInterval(() => {
        this.fromLastSubmitTime++
        if (this.fromLastSubmitTime >= 300) {
          this.fromLastSubmitTime = 0
          this.submitWatchTime(false)
        }
        if (this.isAudition) {
          this.watchedTime++
          // 已登录但试听结束
          if ((this as any).userInfo.UserId !== '-1' && this.isAuditionEnd) {
            this.showDialogTemp = 'showEnroll'
            const videoEl: any = document.querySelector('.live-box video')
            videoEl.style.display = 'none'
            this.player.pause()
            this.stopTimer(true)
            return
          }
          // 试听结束
          if (this.isAuditionEnd) {
            console.log('试听结束')
            this.showDialogTemp = 'goRegister'
            const videoEl: any = document.querySelector('.live-box video')
            videoEl.style.display = 'none'
            this.player.pause()
            this.stopTimer(true)
          }
        }
      }, 1000)
      this.checkState()
    },

    // 停止计时器，停止提交
    stopTimer (endWatch: boolean) {
      this.stopCheckStateTime()
      if (this.timer) {
        window.clearInterval(this.timer)
        this.timer = 0
        return this.submitWatchTime(endWatch)
      } else {
        return Promise.resolve()
      }
    },

    // 失败后尝试重新播放
    tryAgain () {
      if (this.player) {
        // this.checkLiveStateApi()
      } else {
        this.$emit('tryAgain')
        this.createPlayer()
      }
    },

    // 报名-跳转到付款页
    goEnroll () {
      if ((this.liveInfo as any).ClassStatus === 4) {
        let liveInfo = this.liveInfo as any
        this.navPay(liveInfo.TradeNo, liveInfo.OrderId)
      } else {
        this.createOrder()
      }
    },
  },
})
</script>

<style lang="scss" scoped>
.live-box {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  /deep/ {
    .vcp-error-tips {
      opacity: 0;
    }
    .vcp-loading {
      opacity: 0 !important;
    }
    .vcp-slider {
      background: #f6f6f6;
    }
    .vcp-slider-track,.vcp-slider-thumb {
      background-color: #03C9BB;
    }
    .vcp-playtoggle {
      background: url('~assets/class/Play.png') no-repeat center;
      background-size: 40%;
    }
    .vcp-playing .vcp-playtoggle {
      background: url('~assets/class/Pause.png') no-repeat center;
      background-size: 33%;
    }
    .vcp-fullscreen-toggle {
      background: url('~assets/class/Enlarge.png') no-repeat center;
      background-size: 45%;
    }
  }
}
.displayNone {
  display: none;
}
</style>
